package com.msmall.plugin.kindeidtor.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.io.IOUtils;

import com.msmall.base.util.Constants;
import com.msmall.base.util.FileIO;
import com.msmall.base.util.StringUtil;
import com.msmall.base.util.WatermarkerUtil;

/**
 * kindeditor 上传服务，上传到 file/html/user/id/editor/date/
 * @author Administrator
 *
 */
public class ImgUploadService {
	public static final String HOME_PATH_PREFIX_HTML = "file/html/user/";
	public static final String HOME_PATH_PREFIX_WML = "file/wml/user/";
	public static final String HOME_PATH_SUFFIX = "/eidtor/";
	
	/**
	 * 如果name不为空，则图片的名称为name，否则随机一个名称
	 * [0] 路径 file/html/user/id/editor/date/
	 * [1]名称 huangshan.jpg
	 * filename 包括后缀
	 * name 不包括后缀
	 */
	public static String[] saveImage(File file, String filename, String newname, Long userid, String uat) throws Exception{
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
		String datestr = format.format(new Date());
		String path = getHomePath(userid, datestr, uat);
		String ext = filename.substring(filename.indexOf("."));
		File dirs = new File(getAbsoluteHomePath(userid, datestr, uat));
		if(!dirs.exists()){
			dirs.mkdirs();
		}
		String newfilename = newname;
		if(StringUtil.nullOrBlank(newname)){
			newfilename = getFileName();
		}
		newfilename += ext;
		File newFile = new File(getAbsoluteHomePath(userid, datestr, uat) + newfilename);
		File fileToSave = FileIO.getUniqueFile(newFile);
		try {
			IOUtils.copyLarge(new FileInputStream(file), new FileOutputStream(fileToSave));
			WatermarkerUtil.markText(fileToSave, ext, null, 0, 0);
		//	WatermarkerUtil.markImage(fileToSave, ext);
		} catch (IOException e) {
			throw new Exception();
		}
		return new String[]{path, newfilename};
	}
	public static String getAbsoluteHomePath(Long userid, String dateStr, String uat){
		return Constants.ROOTPATH + getHomePath(userid,dateStr, uat);
	}
	/**
	 * 生成图片路径 file/html/user/id/editor/date/
	 * @return
	 */
	public static String getHomePath(Long userid, String datestr, String uat){
		String path = "";
		if(uat.equals(Constants.USER_AGENT_TYPE_HTML)){
			path = HOME_PATH_PREFIX_HTML;
		}
		if(uat.equals(Constants.USER_AGENT_TYPE_WML)){
			path = HOME_PATH_PREFIX_HTML;
		}
		path = path + userid + HOME_PATH_SUFFIX +  datestr +"/";
		return path;
	}
	public static String getFileName(){
		return FileIO.getRandomFileName();
	}
}
